import logging
from logging import Formatter
from datetime import datetime


# 自定义Formatter类
class CustomFormatter(Formatter):
    def format(self, record):
        # 自定义日志格式
        log_format = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [{record.levelname}] [{record.name}] {record.msg % record.args}"
        return log_format.format(record)


# 日志工具类
class Logger:
    def __init__(self, log_file, name='logging', log_level=logging.DEBUG):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(log_level)

        # 创建文件处理器
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(log_level)

        # 创建控制台处理器
        console_handler = logging.StreamHandler()

        # 使用自定义的Formatter
        formatter = CustomFormatter()
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 添加处理器到logger
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

    def critical(self, message):
        self.logger.critical(message)


# 使用示例
if __name__ == "__main__":
    log_tool = Logger("my_logger", "my_log_file.log")

    log_tool.debug("This is a debug message")
    log_tool.info("This is an info message")
    log_tool.warning("This is a warning message")
    log_tool.error("This is an error message")
    log_tool.critical("This is a critical message")